import axios from "axios";
import L from "leaflet";
import Cars from "@/assets/img.js";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import pinia from "@/store/pinia";
import { useMapStore } from "@/store/map";
const mapStore = useMapStore(pinia);

const setLocation = map => {
  // 清除所有的图层
  const allLayers = map._layers; // 注意：_layers是一个内部属性，可能在未来版本中改变

  // 遍历所有图层，并检查它们是否是L.layerGroup的实例
  for (const layerId in allLayers) {
    const layer = allLayers[layerId];

    // 检查图层是否是L.layerGroup的实例
    if (layer instanceof L.LayerGroup) {
      // 如果是，则从地图上移除它
      map.removeLayer(layer);
    }

    // 注意：对于嵌套的layerGroup（即layerGroup中包含其他layerGroup）
  }

  const layerGroup = L.layerGroup().addTo(map);

  let points = [[39.898457, 116.391844]];

  for (let i = 0; i < points.length; i++) {
    L.marker(points[i], {
      icon: L.icon({
        iconUrl: Cars[i%10], // 图标图片的URL
        iconSize: [32, 32], // 图标的大小
        iconAnchor: [15, 15], // 图标的锚点，即图标的位置应该放置在地图上的位置
        popupAnchor: [-3, -76] // 弹出框的锚点，即当你点击图标时，弹出框应该出现在哪个位置
      })
    })
      .addTo(layerGroup)
      .bindTooltip("车牌号", { permanent: true, direction: "top" })
      .openTooltip();

    L.circle(points[i], {
      stroke: true,
      dashArray: "4",
      color: "red",
      fillColor: "#f03",
      fillOpacity: 0.2,
      weight: 2,
      radius: 1200 * 1
    }).addTo(layerGroup);
  }
};

const fetchBasicInfoData = (currentPage, pageSize) => {
  console.log("请求基本数据");
  axios
    .post(
      `http://localhost:5555/api/blog_list/?pageSize=${pageSize}&pageNumber=${currentPage}&sortName=id&sortOrder=desc&_=1595230808893`,
      {
        pageSize,
        currentPage
      }
    )
    .then(
      resp => {
        let resData = [];
        for (let i = 0; i < resp.data.rows.length; i++) {
          resData.push({
            key: resp.data.rows[i].id,
            id: resp.data.rows[i].id,
            title: resp.data.rows[i].title,
            content: resp.data.rows[i].content
              .replace(/<[^>]*>|<\/[^>]*>/gm, "")
              .substring(0, 54),
            datetime: resp.data.rows[i].datetime
          });
        }

        mapStore.basicInfoTableData = resData;
        mapStore.basicInfoTableTotal = resp.data.total;
      },
      err => {
        console.log(err);
        ElMessage({
          message: JSON.stringify(err),
          type: "error"
        });
      }
    );
};

const fetchTrajectoryData = (licensePlate, currentPage, pageSize, range) => {
  console.log("请求轨迹数据");
  axios
    .post(
      `http://localhost:5555/api/blog_list/?pageSize=${pageSize}&pageNumber=${currentPage}&sortName=id&sortOrder=desc&_=1595230808893`,
      {
        licensePlate,
        pageSize,
        currentPage,
        range
      }
    )
    .then(
      resp => {
        let resData = [];
        for (let i = 0; i < resp.data.rows.length; i++) {
          resData.push({
            key: resp.data.rows[i].id,
            id: resp.data.rows[i].id,
            title: resp.data.rows[i].title,
            content: resp.data.rows[i].content
              .replace(/<[^>]*>|<\/[^>]*>/gm, "")
              .substring(0, 54),
            datetime: resp.data.rows[i].datetime
          });
        }

        switch (range) {
          case "Today":
            mapStore.trajectoryTodayTableData = resData;
            mapStore.trajectoryTodayTableTotal = resp.data.total;
            break;
          case "Week":
            mapStore.trajectoryWeekTableData = resData;
            mapStore.trajectoryWeekTotal = resp.data.total;
            break;
          default:
            mapStore.trajectoryMonthTableData = resData;
            mapStore.trajectoryMonthTotal = resp.data.total;
        }
      },
      err => {
        console.log(err);
        ElMessage({
          message: JSON.stringify(err),
          type: "error"
        });
      }
    );
};

export { setLocation, fetchBasicInfoData, fetchTrajectoryData };
